
<template>
  <div class="login-index" v-if="loginPageShow">  
    <div class="swiper">
      <swiper
        :indicator-dots="indicatorDots"
        :autoplay="autoplay"
        :interval="interval"
        :duration="duration"
        :current="current" 
        @change="bindchange"
        style="height:100%;width:100%;"
      >
        <block v-for="item in imgUrls" :key="item">
          <swiper-item>
            <img mode="aspectFill" :src="item" class="slide-image"/>
          </swiper-item> 
        </block>
      </swiper>
      <div class="dots text-center">
        <span class="indicator" v-for="(item,index) in imgUrls"  :key="item" :class="{'indicator-active':current==index}"></span> 
      </div>
    </div>
    <div class="footer-box">
      <div class="footer-btn">
        <div class="main text-center" :style="{'margin-top':wxLoginAnimation&&wxLoginAnimation?'236rpx':'136rpx'}">
          <button class="btn wx-login" :animation="wxLoginAnimation"  open-type="getUserInfo" @getuserinfo="agreeGetUser" ><image src="/static/image/wx-login.png" class="img"></image>使用微信登录</button>
          <div class="btn ph-login"  :animation="phoneLoginAnimation" @click="toLogin()">  手机号登录</div>
        </div>
        <div class="hit-text text-center">点击登录即表示你同意我们的<span>服务条款</span></div>
      </div>
    </div> 
  </div>
</template>

<script>
import * as api from '@/utils/api' ;   
import fillStore from './../../login-page/fill-user-info/store' ;  
const app = getApp()  
export default { 
  onLoad(){    
    let vm = this;
    this.checkLoginState(); 
    let pages = getCurrentPages();//页面栈数组
    let optionsData = pages[pages.length - 1].options//当前页面路由传递的参数   
    //是否是分享进来的 
    this.shareBody={
      ruuid:optionsData.selfUid || '',
      ropenid:optionsData.openId || ''
    }; 
    app.globalData.userDataInfo={
      ruuid:this.shareBody.ruuid || '', //全局保存推荐人ruuid
      share_login:false,
      userRuuid:optionsData.userRuuid || '',
    };    
    if(!this.shareBody.ruuid&&!this.shareBody.ropenid){ 
      if(wx.getStorageSync('refresh_token')&&wx.getStorageSync('h_token')){
        let url = `./../user/main`;
        wx.redirectTo({url});   
      } else {
        setTimeout(()=>{
          vm.loginPageShow=true; 
        },200); 
      }
    }else{
      this.getShareBody();
      if(optionsData.userRuuid){ 
        let url = `./../../shear-page/shear-detail/main?userRuuid=${optionsData.userRuuid}`;
        wx.navigateTo({url});
      }else{
        if(wx.getStorageSync('refresh_token')&&wx.getStorageSync('h_token')){
          let url = `./../user/main`;
          wx.redirectTo({url});   
        } else {
          setTimeout(()=>{
            vm.loginPageShow=true; 
          },200); 
        }
      }
    } 
  },
  onShow: function () {   
    let vm = this;
    if(!wx.getStorageSync('refresh_token')||!wx.getStorageSync('h_token')){
      setTimeout(()=>{
        vm.loginPageShow=true; 
      },200); 
      this.checkLoginState();
    }
    vm.wxLoginAnimation=vm.slideupshow(-70, 1)
    setTimeout( ()=>{
      vm.phoneLoginAnimation=vm.slideupshow(-70, 1)
    }, 200);
  },
         
  data () {
    return {  
      loginPageShow:false,
      headHeight:wx.getStorageSync('headHeight'),
      headPadding:wx.getStorageSync('headPadding'),
      imgUrls: [
        'http://ximihl.oss-cn-hangzhou.aliyuncs.com/photo/1547172446_8081.png',
        'http://ximihl.oss-cn-hangzhou.aliyuncs.com/photo/1547172446_7887.png',
        'http://ximihl.oss-cn-hangzhou.aliyuncs.com/photo/1547172446_1847.png',
        'http://ximihl.oss-cn-hangzhou.aliyuncs.com/photo/1547172446_4059.png'
      ],
      indicatorDots: false,
      autoplay: true,
      interval: 2500,
      duration: 500,
      current:0, 
      wxLoginAnimation:'',
      phoneLoginAnimation:'',
      shareBody:{
        ruuid:'',
        ropenid:''
      }
    }
  },   
  methods: { 
    //  
    shareBrowse(item){
      let vm = this;
      let body={
        openid:item.openid,
        ruuid:item.ruuid,
        ropenid:item.ropenid
      };
      api.postShareBrowse(body).then(res=>{
        console.log(res.data);
      });
    },
    getShareBody(){
      let vm = this;
      let body={
        openid:wx.getStorageSync('openId'),
        ruuid:vm.shareBody.ruuid || '',
        ropenid:vm.shareBody.ropenid || '' 
      }; 
      if(vm.shareBody.ruuid || vm.shareBody.ropenid){ 
        vm.shareBrowse(body);
      } 
    },
    //监听轮播图
    bindchange(e){  
      this.current=e.mp.detail.current; 
    },
    //登录是否是否过期
    checkLoginState() {
      let vm = this;
      wx.checkSession({
        success: function(res) {
          console.log('登录中');
          vm.checkOpenId();
        },
        fail: function(res) {
          console.log('登录过期');
          vm.loginWx();
        }
      })
    },
    //获得openId
    checkOpenId() {
      let vm = this;
      if (!wx.getStorageSync('openId')) {
        vm.loginWx();
      }else{
        vm.getShareBody();
      } 
    },
    //登录微信
    loginWx() {
      let vm = this;
      let myDate= new Date;
      wx.login({
        success: function(res) {
          console.log('登录微信成功，开始获取openId', myDate.getMinutes(), myDate.getSeconds(), myDate.getMilliseconds()); 
          api.wxServer({ code: res.code }).then(res => {
            console.log('openId获取成功', myDate.getMinutes(), myDate.getSeconds(), myDate.getMilliseconds());   
            wx.setStorageSync('openId', res.data.data.openid); 
            vm.getShareBody();
            console.log(res.data.data.openid);
          }).catch(res => {
            wx.showToast({ icon: 'none', title: res.message })  
          });
        }
      });
    },
    //手机号登录
    toLogin(){ 
      app.aldstat.sendEvent('手机登陆');  
      wx.redirectTo({ url:`./../../login-page/bind-phone/main` })
    },
    //用户授权注册
    agreeGetUser(e) { 
      let vm = this;
      if (e.mp.detail.errMsg == 'getUserInfo:fail auth deny') {
        // wx.showModal({
        //   title: '用户未授权',
        //   content: '如需正常使用小程序，需要获取你的基本信息，请您开启授权服务',
        //   showCancel: false,
        // })
      } else {  
        console.log(e.mp.detail);
        fillStore.state.form.nickname=e.mp.detail.userInfo.nickName;
        fillStore.state.form.sex=e.mp.detail.userInfo.gender; 
        if (!wx.getStorageSync('openId')) {
          vm.loginWx();
          // wx.showModal({
          //   title: '提示',
          //   content: '授权失败，请重新授权',
          //   showCancel: false,
          // })
          return;
        } 
        let body={
          identity_type:1,
          identifier:wx.getStorageSync('openId')
        }
        api.userLogin(body).then(res => {    
          app.aldstat.sendEvent('微信登陆');  
          if(res.data.code==300000){  
            let account={
              accid:res.data.data.accid,
              password:res.data.data.password,
              deviceToken:wx.getStorageSync('openId'),
              uuid:res.data.data.uuid,
            }; 
            wx.setStorageSync('account', JSON.stringify(account)); 
            app.globalData.firstTime=true; 
            wx.setStorageSync('refresh_token', res.data.data.refresh_token);
            wx.setStorageSync('h_token', res.data.data.token); 
            if(app.globalData.userDataInfo.share_login&&app.globalData.userDataInfo.userRuuid){
              app.globalData.userDataInfo.share_login=false;
              let url = `./../../shear-page/shear-detail/main?userRuuid=${optionsData.userRuuid}`;
              wx.redirectTo({url});
            } else {
              let url = `./../user/main`;
              wx.redirectTo({url});  
            } 
          }else if(res.data.code==300101){
            //未注册 
            let url = `./../../login-page/fill-user-info/main?loginType=1`;
            wx.redirectTo({url});   
          } else {
            wx.showToast({
              title: res.data.err,
              icon: 'none'
            }) 
          }
        }).catch(res => { 
          wx.showModal({
            title: '提示',
            content: '授权失败，请重新授权',
            showCancel: false,
          })
        }); 
      }
    },
  },
  onShareAppMessage: function(res) { 
    let selfOpenId = wx.getStorageSync('openId');   
    let path = `pages/common/login/main?openId=${selfOpenId}`;  
    return this.onShareAppMessage('',path);
  }, 

}
</script>
 
<style lang="scss" scoped>
.login-index{
  width:100vw;
  height:100vh;
  .swiper{
    height:70vh;
    width:100vw;
    position:relative;
    .dots{
      position:absolute;
      bottom:8vh;
      width:100%; 
      span{
        display:inline-block;
        width:16rpx;
        height:16rpx;
        margin:0 4rpx;
        border-radius:50%;
      }
      .indicator{
        background:rgba(0,0,0,.3);
      }
      .indicator-active{
        background:#fff;
      }
    }
    .slide-image{
      width:100%;
      height:100%; 
    }
  }
  .footer-box{ 
    position:fixed;
    bottom:0;
    height:35vh;
    width:100vw; 
    z-index:10; 
    .footer-btn{
      width:100%;
      height:100%;
      position: relative; 
      .main{
        width:100vw;
        height:190rpx;
        position: absolute;
        top:0;  
        .btn{
          width:468rpx;
          height:80rpx; 
          border-radius:40rpx;
          font-size:32rpx;
          margin:auto;
          display:flex;
          align-items:center;
          justify-content:center;
          &:active{
            opacity:.7;
          }
        }
        .wx-login{
          color:#fff;
          background:#13BB08;
          .img{
            width:40rpx;
            height:34rpx;
            margin-right:8rpx;
          }
        }
        .ph-login{
          color:#878B8F;
          background:#fff;
          border:1rpx solid #D3D7DC;
          margin-top:24rpx;
        }
      }
      .hit-text{
        width:100%; 
        position: absolute;
        bottom:50rpx; 
        color:#878B8F;
        font-size:24rpx;
        span{
          text-decoration:underline;
        }
      }
      &:after {
        width: 200%;
        height: 100%;
        position: absolute;
        left: -50%;
        top:0;
        z-index: -1;
        content: '';
        border-radius:50% 50% 0 0;
        background:linear-gradient(#fff,#fff);
      }
    } 
  }
}
</style>
